﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class System_ProductManagement : System.Web.UI.Page
{
    const int idxCode = 4;
    const int idxName = 5;
    const int idxModule = 6;
    const int idxColor = 7;
    const int idxPrice = 8;

    const string SystemError_ProductCodeLength3 = "SystemError_ProductCodeLength3";
    const string SystemError_ProductPriceNotNumber = "SystemError_ProductPriceNotNumber";
    const string SystemError_ProductNameEmpty = "SystemError_ProductNameEmpty";
    const string SystemError_ProductColorEmpty = "SystemError_ProductColorEmpty";
    const string SystemError_ProductModuleEmpty = "SystemError_ProductModuleEmpty";
    

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //set state to view
            SetPage(3);
        }
    }

    protected void GridViewProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // Convert the row index stored in the CommandArgument
        // property to an Integer.
        int index=0; 

        switch (e.CommandName)
        {
            case "DoUpdate":
                index = PublicDefine.GetSelectRowIndex(e);
                // Get the data from current row and set to the detail information area for update
                this.HiddenFieldProductID.Value = GridViewProductsList.DataKeys[index].Values[0].ToString();
                this.DropDownListProductList.SelectedValue = GridViewProductsList.DataKeys[index].Values[1].ToString();
                this.TextBoxProductTypeCode.Text = GridViewProductsList.Rows[index].Cells[idxCode].Text.Substring(0,4);
                this.TextBoxProductCode.Text = GridViewProductsList.Rows[index].Cells[idxCode].Text.Substring(4);
                this.TextBoxProductName.Text = GridViewProductsList.Rows[index].Cells[idxName].Text;
                this.TextBoxProductModule.Text = GridViewProductsList.Rows[index].Cells[idxModule].Text;
                this.TextBoxProductColor.Text = GridViewProductsList.Rows[index].Cells[idxColor].Text;
                this.TextBoxProductPrice.Text = GridViewProductsList.Rows[index].Cells[idxPrice].Text;
                //Set the visiblility of button
                SetPage(2);
                break;
            case "DoDelete":
                index = PublicDefine.GetSelectRowIndex(e);
                int productid = int.Parse(GridViewProductsList.DataKeys[index].Values[0].ToString());
                DeleteProduct(productid);
                GridViewProductsList.DataBind();
                break;
        }
    }

    

    /// <summary>
    /// state
    /// 1  Addnew
    /// 2  Update
    /// 3  View
    /// </summary>
    /// <param name="State"></param>
    void SetPage(int State)
    {

        switch (State)
        {
            case 1: //Addnew
                this.DropDownListProductTopType.Enabled = true;
                this.ButtonAdd.Visible = true;
                this.ButtonCancle.Visible = true;
                this.ButtonUpdate.Visible = false;
                this.ButtonAddMore.Visible = true;
                this.ButtonAddNew.Visible = false;
                break;
            case 2: //Update
                this.DropDownListProductTopType.Enabled = false;
                this.ButtonAdd.Visible = false;
                this.ButtonCancle.Visible = true;
                this.ButtonUpdate.Visible = true;
                this.ButtonAddMore.Visible = false;
                this.ButtonAddNew.Visible = false; 
                break;
            case 3: //View
                this.DropDownListProductTopType.Enabled = false;
                this.ButtonAdd.Visible = false;
                this.ButtonCancle.Visible = false;
                this.ButtonUpdate.Visible = false;
                this.ButtonAddMore.Visible = false;
                this.ButtonAddNew.Visible = true; 
               
                break;
        }
    }


    private bool CheckInput()
    {
        Hashtable errors = ValidateInput();
        if (0 == errors.Count)
        {
            return true;
        }
        else
        {
            ShowErrors(errors);
            return false;
        }
    }


    Hashtable ValidateInput()
    {
        Hashtable errors = new Hashtable();
        string code = TextBoxProductCode.Text.Trim();
        if (3 != code.Length)
        {
            errors.Add(SystemError_ProductCodeLength3, SystemError_ProductCodeLength3);
        }
        try
        {
            int.Parse(code);
        }
        catch
        {
            errors.Add(SystemError_ProductCodeLength3, SystemError_ProductCodeLength3);
        }

        decimal price = 0;
        try
        {
            price = decimal.Parse(TextBoxProductPrice.Text);
        }
        catch
        {
            errors.Add(SystemError_ProductPriceNotNumber, SystemError_ProductPriceNotNumber);
        }
        if (0 == TextBoxProductName.Text.Trim().Length)
        {
            errors.Add(SystemError_ProductNameEmpty, SystemError_ProductNameEmpty);
        }
        if (0 == TextBoxProductColor.Text.Trim().Length)
        {
            errors.Add(SystemError_ProductColorEmpty, SystemError_ProductColorEmpty);
        }
        if (0 == TextBoxProductModule.Text.Trim().Length)
        {
            errors.Add(SystemError_ProductModuleEmpty, SystemError_ProductModuleEmpty);
        }
        return errors;
    }

    void ShowErrors(Hashtable errors)
    {
        string errormessage = "";
        foreach (string errorkey in errors.Keys)
        {
            errormessage += (string)GetGlobalResourceObject(PublicDefine.GlobalResource, errorkey) + " ";
        }
        LabelError.Text = errormessage;
    }

    bool CheckForAddNew()
    {

        DAO.ProductInfo newproduct = new DAO.ProductInfo();
        newproduct.ProductName = TextBoxProductName.Text.Trim();
        newproduct.ProductColor = TextBoxProductColor.Text.Trim();
        newproduct.ProductCode = TextBoxProductTypeCode.Text.Trim() + TextBoxProductCode.Text.Trim();
        newproduct.ProductModule = TextBoxProductModule.Text.Trim();

        Hashtable errors = SystemBL.CheckForAddNew(newproduct);

        if (0 == errors.Count)
        {
            return true;
        }
        else
        {
            ShowErrors(errors);
            return false;
        }
    }


    bool CheckForUpdate()
    {
        DAO.ProductInfo product = new DAO.ProductInfo();
        product.ProductID = int.Parse(HiddenFieldProductID.Value.ToString());
        product.ProductName = TextBoxProductName.Text.Trim();
        product.ProductColor = TextBoxProductColor.Text.Trim();
        product.ProductCode = TextBoxProductTypeCode.Text.Trim() + TextBoxProductCode.Text.Trim();
        product.ProductModule = TextBoxProductModule.Text.Trim();

        Hashtable errors = SystemBL.CheckForUpdate(product);
        if (0 == errors.Count)
        {
            return true;
        }
        else
        {
            ShowErrors(errors);
            return false;
        }


    }

    private bool UpdateProduct()
    {
        //check the input
        if (!CheckInput())
        {
            return false;
        }
        //check update
        if (!CheckForUpdate())
        {
            return false;
        }
        string productcode = TextBoxProductTypeCode.Text.Trim() + TextBoxProductCode.Text.Trim();
        decimal price =decimal.Parse(TextBoxProductPrice.Text);

        DAO.ProductInfo product = new DAO.ProductInfo();
        product.ProductID = int.Parse(this.HiddenFieldProductID.Value.Trim());
        product.ProductTypeID = int.Parse(DropDownListProductList.SelectedValue);
        product.ProductCode = productcode;
        product.ProductName = TextBoxProductName.Text.Trim();
        product.ProductModule = TextBoxProductModule.Text.Trim();
        product.ProductColor = TextBoxProductColor.Text.ToString().Trim();
        product.ProductPrice = decimal.Parse(price.ToString().Trim());

        SystemBL.UpdateProduct(product);

        return true;
    }

    private bool AddProduct()
    {
        //check the input
        if (!CheckInput())
        {
            return false;
        }
        //check for add new
        if (!CheckForAddNew())
        {
            return false;
        }

        string productcode = TextBoxProductTypeCode.Text.Trim() + TextBoxProductCode.Text.Trim();
        decimal price = decimal.Parse(TextBoxProductPrice.Text);

        DAO.ProductInfo product = new DAO.ProductInfo();
        product.ProductTypeID = int.Parse(DropDownListProductList.SelectedValue);
        product.ProductCode = productcode;
        product.ProductName = TextBoxProductName.Text.Trim();
        product.ProductModule = TextBoxProductModule.Text.Trim();
        product.ProductColor = TextBoxProductColor.Text.ToString().Trim();
        product.ProductPrice = decimal.Parse(price.ToString().Trim());

        SystemBL.AddNewProduct(product);

        return true;
    }

    private bool DeleteProduct(int productid)
    {
        SystemBL.DeleteProduct(productid);
        return true;
    }
   
    private void ClearEditRegion()
    {
        this.HiddenFieldProductID.Value = "";
        this.DropDownListProductList.DataBind();
        this.DropDownListProductList.SelectedIndex = 0;
        this.TextBoxProductTypeCode.Text = "";
        this.TextBoxProductCode.Text = "";
        this.TextBoxProductName.Text = "";
        this.TextBoxProductModule.Text = "";
        this.TextBoxProductColor.Text = "";
        this.TextBoxProductPrice.Text = "";
        this.LabelError.Text = "";
    }    
    
    private void SetProductTypeCode()
    {
        if (-1 < DropDownListProductList.SelectedIndex)
        {
            int producttypeid = 0;
            try
            {
                producttypeid = int.Parse(DropDownListProductList.SelectedValue.ToString());
            }
            catch
            {
                return;
            }

            string prefixCode = SystemBL.GetProductTypeCode(producttypeid).Trim();

            TextBoxProductTypeCode.Text = prefixCode;
        }
    }

    protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        if (UpdateProduct())
        {
            //set state to view
            SetPage(3);
            GridViewProductsList.DataBind();
            ClearEditRegion();
        }
        else
        {
        }
        
    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        if (AddProduct())
        {
            //set state to view
            SetPage(3);
            GridViewProductsList.DataBind();
            ClearEditRegion();
        }
        else
        {

        }
    }
    protected void ButtonAddMore_Click(object sender, EventArgs e)
    {
        if (AddProduct())
        {
            //set to add new mode
            SetPage(1);
            GridViewProductsList.DataBind();
            ClearEditRegion();
            SetProductTypeCode();
        }
        else
        {

        }
    }
    protected void ButtonAddNew_Click(object sender, EventArgs e)
    {
        //set to add new mode
        SetPage(1);
        GridViewProductsList.DataBind();
        ClearEditRegion();     
        SetProductTypeCode();           
    }
    protected void ButtonCancle_Click(object sender, EventArgs e)
    {
        //set state to view
        SetPage(3);
        GridViewProductsList.DataBind();
        ClearEditRegion();
    }
    protected void DropDownListProductTopType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (-1 < DropDownListProductTopType.SelectedIndex)
        {
            this.DropDownListProductList.DataBind();
            SetProductTypeCode();
        }
    }
    protected void DropDownListProductList_SelectedIndexChanged(object sender, EventArgs e)
    {
        SetProductTypeCode();
    }


    protected void DrpProductTypeList_SelectedIndexChanged(object sender, EventArgs e)
    {
        Parameter orderby = ObjectDataSource_Products.SelectParameters["orderby"];
        Parameter code = new Parameter("type", System.TypeCode.Int32, DrpProductTypeList.SelectedValue);
        ObjectDataSource_Products.SelectParameters.Clear();
        ObjectDataSource_Products.SelectParameters.Add(code);
        ObjectDataSource_Products.SelectParameters.Add(orderby);
        ObjectDataSource_Products.DataBind();
    }

    protected void ButtonFind_Click(object sender, EventArgs e)
    {
        Parameter orderby = ObjectDataSource_Products.SelectParameters["orderby"];
        Parameter code = new Parameter("productcode",System.TypeCode.String, TextBoxFindCode.Text.Trim());
        ObjectDataSource_Products.SelectParameters.Clear();
        ObjectDataSource_Products.SelectParameters.Add(code);
        ObjectDataSource_Products.SelectParameters.Add(orderby);
        ObjectDataSource_Products.DataBind();
    }

    protected void GridViewProductsList_Sorting(object sender, GridViewSortEventArgs e)
    {
        ObjectDataSource_Products.SelectParameters["orderby"].DefaultValue = e.SortExpression;
        GridViewProductsList.DataBind();
        e.Cancel = true;        
    }
    
}
